﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Threading;
using System.Diagnostics;


namespace SilverSmug
{
    public partial class Page : UserControl
    {
        string nickName = "cabler";
        List<Album> albumList;
        int row = 0, col = 0;

        public Page()
        {
            InitializeComponent();
            attemptLogin();
        }       

        void attemptLogin()
        {
            String req = SmugAcc.makeRequestURL(SmugAcc.loginMethod, "APIKey=" + SmugAcc.appKey);
            SmugAcc.sendRequest(req, getSessionID);
        }

        private void getSessionID(XDocument xDoc)
        {
            XElement elem3 = xDoc.Descendants().ElementAt(0);
            //need error handling here for mt return
            SmugAcc.sessionID = elem3.Element("Login").Element("Session").Attribute("id").Value;
            requestAlbums();
        }

        private void requestAlbums()
        {
            String req = SmugAcc.makeRequestURL(SmugAcc.getAlbumsMethod,
                "sessionID=" + SmugAcc.sessionID, "NickName=" + nickName, "Pretty=1");
            SmugAcc.sendRequest(req, parseAlbums);
        }

        private void parseAlbums(XDocument xDoc)
        {
            XElement respE = xDoc.Element("rsp");
            if (respE.Attribute("stat").Value != "ok")
            {
                //MyText.Text = "Invalid Response Received: \n" + xDoc.ToString();
                return;
            }

            /*
             * Pulls in all albums with a valid category only - may 
             * need to extend this, but I think all albums must have a
             * category
             */
            var albums = from album in respE.Element("Albums").Descendants()
                         where album.Attribute("id") != null
                         where album.Attribute("id").Value != ""
                         where album.Element("Category") != null
                         select new Album
                         {
                             id = (string)album.Attribute("id"),
                             key = (string)album.Attribute("Key"),
                             title = (string)album.Attribute("Title"),
                             categoryName = (string)album.Element("Category").Attribute("Name").Value
                         };
            albumList = new List<Album>();
            foreach (Album album in albums)
            {
                //MyText.Text += "\nFound album: " + album.title + " in " + album.categoryName;
                albumList.Add(album);
            }
            retrieveImages();
            createAlbumHolders();

        }

        private void retrieveImages()
        {
            foreach (Album album in albumList)
            {
                Album albumRef = album;
                album.retrieveImages(delegate()
                {
                    loadFirstAlbumImage(albumRef);

                });
            }
        }

        private void createAlbumHolders()
        {

            int albumSize = albumList.Count();
            if (albumSize == 0)
            {
                //need to show error here
                return;
            }
            int numCols = 5;
            int numRows = albumSize / numCols;
            //GridLayout.ShowGridLines = true;

            for (int i = 0; i < numRows; i++)
            {
                RowDefinition rd = new RowDefinition();
                rd.Height = new GridLength(200);              
                GridLayout.RowDefinitions.Add(rd);
            }

            for (int i = 0; i < numCols; i++)
            {
                ColumnDefinition cd = new ColumnDefinition();
                cd.Width = new GridLength(200);
                GridLayout.ColumnDefinitions.Add(cd);
            }
        }

        public void loadFirstAlbumImage(Album album)
        {

            Debug.WriteLine("Processing: " + album.title);
            //Make sure this is run on the UI thread
            String url = album.getImages().First().url;
            if (url == null)
            {
                Debug.WriteLine("Problem with " + album.title + " image: " + album.getImages().First().id);
            }
            else
            {

                Dispatcher.BeginInvoke(delegate
                {
                    showImage(url, row, col++);

                });
            }

            if (col == 5)
            {
                col = 0;
                row++;
            }

        }

        public void showImage(String imageUrl, int row, int col)
        {
            Grid thumbGrid = new Grid();
            ColumnDefinition cd = new ColumnDefinition();
            cd.Width = new GridLength(150);
            thumbGrid.ColumnDefinitions.Add(cd);
            thumbGrid.ColumnDefinitions.Add(new RowDefinition());
            thumbGrid.ColumnDefinitions.Add(new RowDefinition());
            
            Uri uri = new Uri(imageUrl);
            BitmapImage imgSrc = new BitmapImage();
            imgSrc.SetValue(BitmapImage.UriSourceProperty, uri);
            Image newI = new Image();
            newI.Source = imgSrc;
            newI.SetValue(Grid.RowProperty, 0);
            newI.SetValue(Grid.ColumnProperty, 0);
            thumbGrid.Children.Add(thumbGrid);

            


            Border border = new Border();
            border.Width = 104;
            border.Height = 104;
            border.BorderThickness = new Thickness(2);
            border.BorderBrush = new SolidColorBrush(Colors.DarkGray);
            border.SetValue(Grid.RowProperty, row);
            border.SetValue(Grid.ColumnProperty, col);
            border.Child = newI;

            GridLayout.Children.Add(border);
            ToolTipService.SetToolTip(newI, imageUrl);

        }        


    }
}
